package channel

import (
	"encoding/hex"
	"encoding/json"
	"fmt"

	"github.com/hyperledger/fabric-protos-go/common"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/ledger"
)

type F_Block_Info struct {
	BlockNumber int
	DataHash    string
	PreHash     string
	BlockHash   string
	TxCount     int
	Size        int
}

func GetBlockInfo(client *ledger.Client, blockNumber uint64) (*F_Block_Info, error) {
	var block *common.Block
	var blk *F_Block_Info
	blk = &F_Block_Info{}
	block, err := client.QueryBlock(blockNumber)
	if err != nil {
		return nil, err
	}

	fmt.Printf("  |---> 区块: \n%#v\n", block)
	//fmt.Printf("区块编号: %v\n", block.Header.Number)
	//fmt.Printf("区块Hash:\n%v\n", hex.EncodeToString(block.Header.DataHash))

	b, err := json.Marshal(block)
	if err != nil {
		fmt.Println("Umarshal failed:", err)
		return nil, err
	}
	blk.BlockNumber = int(blockNumber)
	blk.DataHash = hex.EncodeToString(block.Header.DataHash)
	blk.PreHash = hex.EncodeToString(block.Header.PreviousHash)
	blk.TxCount = len(block.Data.Data)
	blk.Size = len(b) / 1024

	//fmt.Printf("  |---> 未组织数据Size=%d KB\n", len(block.Data.XXX_unrecognized)/1024)
	//count := blk.TxCount
	//for i := 0; i < count; i++ {
	//arB := block.Data.Data[i]
	//fmt.Printf("  |---> 数组[%d]Size=%d KB\n", i, len(arB)/1024)
	//}
	//count = len(block.Metadata.Metadata)
	//for i := 0; i < count; i++ {
	//arB := block.Metadata.Metadata[i]
	//fmt.Printf("  |---> 数组[%d]Size=%d KB\n", i, len(arB)/1024)
	//}

	//block.Metadata.XXX_unrecognized

	return blk, nil
}
